package dk.pekilidi.dod.util;

import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

/**
 * User: msp
 * Date: Mar 19, 2008
 * Time: 12:56:39 PM
 */
public class PojoSanityChecker {

    //TODO add support for methods annoted with constraint NULL / not NULL

    public static boolean isSane(Object o) throws NoSuchMethodException {
        Method[] methods = o.getClass().getMethods();
        System.out.println("Testing class: " + o.getClass());
        boolean result = true;
        for (Method method : methods) {
            System.out.println("Testing method: " + method.getName());
            if (method.getName().startsWith("get")) {
                if (method.getParameterTypes().length != 0) {
                    System.out.println(new StringBuilder().append("Getter method had arguments, ").
                            append("indicating this may not be a true POJO").
                            append(" ... skipping method call").toString());
                    continue;
                }
                try {
                    if (method.invoke(o) == null) {
                        System.out.println(new StringBuilder().append("Field Data was null, at: ").
                                append(new Date().toString()).toString());
                        result = false;
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    if (e.getCause() instanceof NullPointerException) {
                        System.out.println("Encountered NPE in, which indicates logic that might need manual sanity check!");
                    }
                    e.printStackTrace();
                }
            } else {
                System.out.println("Skipping non-getter: " + method.getName());
            }
        }
        return result;
    }
}
